package cn.com.twoke.game.server.handler;

import cn.com.twoke.game.common.entity.message.StopGameMessage;
import cn.com.twoke.game.common.handler.MessageHandler;
import cn.com.twoke.game.common.utils.MessageUtil;
import cn.com.twoke.game.server.cache.GameRoomCache;
import cn.com.twoke.game.server.cache.OnlineUserCache;
import cn.com.twoke.game.server.entity.GameRoom;

import java.io.IOException;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

public class StopGameMessageHandler implements MessageHandler<StopGameMessage> {

    @Override
    public void handle(Selector selector, SocketChannel channel, StopGameMessage message) throws IOException {
        GameRoom room = GameRoomCache.getByRoomId(message.getRoomId());

        if (null != room) {
            if (!room.getRoomMasterId().equals(message.getUserId()) ||  (room.getRoomMasterId().equals(message.getUserId()) && message.isStopCurrentUser())) {
                MessageUtil.writeMessage(OnlineUserCache.CACHE.get(room.getRoomMasterId()), message);
            }
            room.getPlayerIds().forEach(item -> {
                if (!item.equals(message.getUserId()) ||  (item.equals(message.getUserId()) && message.isStopCurrentUser())) {
                    MessageUtil.writeMessage(OnlineUserCache.CACHE.get(item), message);
                }
            });
            GameRoomCache.remove(room.getRoomMasterId());
        }
    }


}
